package com.wjy.icu.emqx.listener;


import cn.hutool.core.util.HexUtil;
import cn.hutool.json.JSONUtil;
import com.wjy.icu.Delay.DelayQueueManager;
import com.wjy.icu.Delay.DelayTask;
import com.wjy.icu.Delay.EquipmentMq;
import com.wjy.icu.common.CacheManage;
import com.wjy.icu.domain.vo.MqttConnectedVo;
import com.wjy.icu.domain.vo.MqttDisconnectedVo;
import com.wjy.icu.domain.vo.UpData;
import com.wjy.icu.emqx.client.MqttPushClient;
import com.wjy.icu.emqx.config.MqttConfig;
import com.wjy.icu.emqx.utils.MqttUtils;
import com.wjy.icu.service.IMqttService;
import com.wjy.icu.websocket.server.WebSocketServer;
import lombok.SneakyThrows;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Description:
 * @author: wangjunyong
 * @date: 2021/9/24 14:58
 */
@Component
public class PushCallback implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(PushCallback.class);
    @Autowired
    private MqttConfig mqttConfig;
    private static MqttClient client;
    @Autowired
    private MqttPushClient mqttPushClient;
    @Autowired
    private IMqttService mqttService;
    @Autowired
    CacheManage cacheManage;
    @Autowired
    DelayQueueManager delayQueueManager;

    public  static PushCallback PushCallback ;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        System.out.println("初始化");
        PushCallback = this;
        PushCallback.delayQueueManager = this.delayQueueManager;
        PushCallback.cacheManage = this.cacheManage;
    }
    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("连接断开，可以做重连");
        if (client == null || !client.isConnected()) {
            mqttConfig.getMqttPushClient();
        }
    }
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
//        logger.info("接收消息主题 : " + topic);
//        logger.info("接收消息Qos : " + mqttMessage.getQos());
//        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));
        byte[] payload = mqttMessage.getPayload();
        String s = MqttUtils.Bytes2HexString(payload);
//        logger.info("sb1:"+s);
        if (topic.contains("/connected")){
            logger.info("设备上线、连接上");
            MqttConnectedVo connectedVo = JSONUtil.toBean(new String(mqttMessage.getPayload()), MqttConnectedVo.class);
            String mac = connectedVo.getClientid();
            mqttService.equitmentUpdateStatus(mac,1);
            if (mac.startsWith("34")) {
                if (cacheManage.isExist(mac + "up")) {
                    logger.info("当前上线的设备" + mac + "/up,已存在");
                } else {
                    logger.info("当前上线的设备" + mac + "/up,不存在，加入redis");
                    cacheManage.set(mac + "up", "");
                    logger.info("redis完成");
                    //延迟命令  //1.订阅mac
                    delayQueueManager.put(new DelayTask(new EquipmentMq(0, mac), 500));
                    logger.info("延迟命令发送完成");
                }
                //延迟命令  //2.发送设备上传指令
                delayQueueManager.put(new DelayTask(new EquipmentMq(1, mac), 500));
                logger.info("延迟命令发送完成");
            }

        }else if (topic.contains("/disconnected")){
            logger.info("设备下线、断开");
            MqttDisconnectedVo disconnectedVo = JSONUtil.toBean(new String(mqttMessage.getPayload()), MqttDisconnectedVo.class);
            String mac = disconnectedVo.getClientid();
            mqttService.equitmentUpdateStatus(mac,0);
            if(cacheManage.isExist(mac+"up")){
                cacheManage.remove(mac+"up");
                logger.info("redis完成");
            }
        }else if (topic.contains("/up")){
//            logger.info("设备上传数据");
            if(s.startsWith("6802")) {
                UpData upData = MqttUtils.upPayloadParse(s);
//                logger.info("解析出来的结果是：" + upData);
                String mac = topic.substring(0, topic.indexOf("/up"));
                logger.info("mac："+mac);
                logger.info("数据："+s);
                mqttService.update(upData, mac);
                WebSocketServer.sendMacInfo(null, mac);
            }
        }else {
            logger.info("其他类型");
        }
    }

    @SneakyThrows
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        MqttMessage message = iMqttDeliveryToken.getMessage();

//        logger.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }
}
